package com.sciencep.pro.core.common.utils;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sciencep.pro.common.config.Constant;
import com.sciencep.pro.core.domain.entity.MailInfo;
import com.sciencep.pro.core.service.IMailInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

@Component
@Slf4j
public class SendMailUtils {

    @Autowired
    IMailInfoService mailInfoService;


    public boolean send(String sAddrList, String sMessage, String sSubject, boolean bIsHtml, File[] aFiles) {

        MailInfo mailInfo = mailInfoService.getOne(new LambdaQueryWrapper<MailInfo>().eq(MailInfo::getIsDel, Constant.IsDelete.NO));

        String sSmtpHost = mailInfo.getServerHost();
        String sSmtpUser = mailInfo.getUserName();
        String sSmtpPass = mailInfo.getPassword();
        String sFromMail = mailInfo.getSendFrom();
        String sCCList = mailInfo.getSendCc();

        log.info("获得邮件配置参数：");
        log.info("sSmtpUser=" + sSmtpUser);
        log.info("sSmtpPass=" + sSmtpPass);
        log.info("sFromMail=" + sFromMail);
        log.info("sCCList=" + sCCList);

        return send(sSmtpHost, sSmtpUser, sSmtpPass, sFromMail, sAddrList, sCCList, sMessage, sSubject, bIsHtml, aFiles);
    }

    public static boolean send(String sSmtpHost, final String sSmtpUser, final String sSmtpPass, String sFromMail, String sAddrList, String sCCList, String sMessage, String sSubject, boolean bIsHtml, File[] aFiles) {
        if (sAddrList.length() == 0) {
            return false;
        }

        try {
            boolean isAuth = false;
            String charset = "utf-8";
            String displayName = "";
            String[] tos = sAddrList.split(",");
            String[] ccs = null;
            if (sCCList.length() > 0) {
                ccs = sCCList.split(",");
            } else {
                ccs = new String[0];
            }

            Session session = null;
            Properties props = System.getProperties();
            props.put("mail.smtp.host", sSmtpHost);
            // 服务器需要身份认证
            if (isAuth) {
                log.info("需要进行服务器身份认证");
                props.put("mail.smtp.auth", "true");
                //生成认证的Authenticator

                Authenticator authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(sSmtpUser,
                                sSmtpPass);
                    }
                };

                session = Session.getDefaultInstance(props, authenticator);
            } else {
                props.put("mail.smtp.auth", "false");
                session = Session.getDefaultInstance(props, null);
            }
            //是否debug
            session.setDebug(true);
            Transport trans = session.getTransport("smtp");

            //多个接收人
            InternetAddress[] address = new InternetAddress[tos.length];
            for (int i = 0; i < address.length; i++) {
                address[i] = new InternetAddress(tos[i]);
                log.info("接收人地址：" + address[i]);
            }

            // 多个抄送人
            InternetAddress[] ccAddress = new InternetAddress[ccs.length];
            for (int i = 0; i < ccAddress.length; i++) {
                ccAddress[i] = new InternetAddress(ccs[i]);
                log.info("抄送人地址：" + ccAddress[i]);
            }

            //连接服务器
            log.info("连接服务器");
            trans.connect(sSmtpHost, sSmtpUser, sSmtpPass);

            //生成发送的消息
            log.info("生成发送的消息");
            Message msg = new MimeMessage(session);

            //邮件的地址及别名
            Address fromAddress = new InternetAddress(sFromMail, displayName);

            //设置
            log.info("设置发送人地址：" + fromAddress);
            msg.setFrom(fromAddress);

            //设置接收人地址
            log.info("设置接收人地址");
            msg.setRecipients(Message.RecipientType.TO, address);

            //设置抄送人地址
            log.info("设置抄送人地址");
            if (sCCList.length() > 0) {
                msg.setRecipients(Message.RecipientType.CC, ccAddress);
            }

            //设置发送主题
            log.info("设置发送主题" + sSubject);
            msg.setSubject(sSubject);

            //部件
            Multipart mp = new MimeMultipart();

            //body部件
            MimeBodyPart mbp = new MimeBodyPart();

            //判断发送的是否是html格式
            if (bIsHtml) {// 如果是html格式
                log.info("内容是html格式");
                mbp.setContent(sMessage, "text/html;charset=" + charset);
            } else {
                mbp.setText(sMessage);
            }
            //将该正文部件加入到整体部件
            mp.addBodyPart(mbp);

            if (aFiles != null && aFiles.length > 0) {// 判断是佛有附件
                //存在附件就将附件全部加入到BodyPart
                for (File file : aFiles) {
                    mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(file); // 得到数据源
                    mbp.setDataHandler(new DataHandler(fds)); // 得到附件本身并至入BodyPart
                    mbp.setFileName(MimeUtility.encodeText(fds.getName())); // 得到文件名同样至入BodyPart
                    mp.addBodyPart(mbp);
                }
            }
            // Multipart加入到信件
            msg.setContent(mp);

            // 设置信件头的发送日期
            log.info("设置信件头的发送日期");
            msg.setSentDate(new Date());

            // 发送信件
            log.info("发送信件");
            msg.saveChanges();

            //发送
            log.info("发送");
            trans.sendMessage(msg, msg.getAllRecipients());

            //结束
            log.info("结束");
            trans.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            log.error("NoSuchProviderException", e);
            return false;
        } catch (MessagingException e) {
            log.error("MessagingException", e);
            e.printStackTrace();
            return false;
        } catch (UnsupportedEncodingException e) {
            log.error("UnsupportedEncodingException", e);
            e.printStackTrace();
            return false;
        }

        return true;
    }


}
